package tw.asap.plus.ui.custom;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPropertyAnimatorListenerAdapter;
import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.support.v7.app.AlertDialog;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import tw.asap.plus.R;
import tw.asap.plus.presenter.CartCheckoutListener;
import tw.asap.plus.presenter.CartListOpenListener;
import tw.asap.plus.ui.adapter.CartListAdapter;
import tw.asap.plus.utils.ScreenUtil;


/**
 * Created by Yax on 15/11/7.
 */
public class CartView extends FrameLayout {

    @InjectView(R.id.amt)
    TextView amt;
    @InjectView(R.id.bt_gocheck)
    TextView btGocheck;
    @InjectView(R.id.floatingButton)
    FloatingActionButton floatingButton;
    TextView indicator;
    CartListOpenListener openListener;
    View mView;
    Context mContext;
    private static final int ANIMATION_DURATION = 250;
    private static final int ANIMATION_FADE_DURATION = 180;
    @InjectView(R.id.list_view)
    ListView listView;
    @InjectView(R.id.sbv)
    SlideBottomPanel sbv;
    private CartCheckoutListener checkoutListener;
    CartListAdapter adapter;
    public CartView(Context context) {
        super(context);
        this.mContext = context;
        initView(mContext);
    }

    public CartView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        initView(mContext);
    }


    public CartView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        initView(mContext);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public CartView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        this.mContext = context;
        initView(mContext);
    }


    public void hideCartBar() {
        animateViewOut(0);
    }

    public void showCartBar() {
        animateViewIn();
    }

    public void setQuantityText(int num) {
        if (num == 0) {
            indicator.setVisibility(View.GONE);
        } else {
            if (num > 99) {
                indicator.setTextSize(TypedValue.COMPLEX_UNIT_SP, 8);
            }
            indicator.setText(String.valueOf(num));
            indicator.setVisibility(VISIBLE);
        }
    }

    public void setSummery(String summery) {
        amt.setText("共 $".concat(summery));
    }


    private void initView(Context context) {

        mView = LayoutInflater.from(context).inflate(R.layout.view_cart, this);
        ButterKnife.inject(mView);
        int api = Build.VERSION.SDK_INT;
        if (api >= 21) {
            int gap = ScreenUtil.dip2px(context, 16);
            LayoutParams lp = (LayoutParams) floatingButton.getLayoutParams();
            lp.setMargins(gap, gap, gap, gap);
            floatingButton.setLayoutParams(lp);
        }

        indicator = (TextView) LayoutInflater.from(context).inflate(R.layout.view_text_indicator, null);
        LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        indicator.setLayoutParams(layoutParams);
        addView(indicator, layoutParams);
    }


    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);

        final int width = indicator.getMeasuredWidth();
        final int height = indicator.getMeasuredHeight();

        int indicatorLeft = floatingButton.getRight() - width / 2 - ScreenUtil.dip2px(getContext(), 3);
        int indicatorTop = floatingButton.getTop();
        int indicatorRight = indicatorLeft + width;
        int indicatorBottom = indicatorTop + height;

        if (Build.VERSION.SDK_INT < 21) {
            int floatingButtonPadding = floatingButton.getPaddingRight() / 2;
            indicatorLeft -= floatingButtonPadding;
            indicatorRight -= floatingButtonPadding;
            indicatorBottom += floatingButtonPadding / 2;
            indicatorTop += floatingButtonPadding / 2;
        }

        indicator.layout(indicatorLeft, indicatorTop, indicatorRight, indicatorBottom);
    }

    private void animateViewIn() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            ViewCompat.setTranslationY(mView, mView.getHeight());
            ViewCompat.animate(mView)
                    .translationY(0f)
                    .setInterpolator(new FastOutSlowInInterpolator())
                    .setDuration(ANIMATION_DURATION)
                    .setListener(new ViewPropertyAnimatorListenerAdapter() {
                        @Override
                        public void onAnimationStart(View view) {
                        }

                        @Override
                        public void onAnimationEnd(View view) {
                        }
                    }).start();
        } else {
            Animation anim = AnimationUtils.loadAnimation(mView.getContext(),
                    android.support.design.R.anim.design_snackbar_in);
            anim.setInterpolator(new FastOutSlowInInterpolator());
            anim.setDuration(ANIMATION_DURATION);
            anim.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationEnd(Animation animation) {
                }

                @Override
                public void onAnimationStart(Animation animation) {
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                }
            });
            mView.startAnimation(anim);
        }
    }

    private void animateViewOut(final int event) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            ViewCompat.animate(mView)
                    .translationY(mView.getHeight())
                    .setInterpolator(new FastOutSlowInInterpolator())
                    .setDuration(ANIMATION_DURATION)
                    .setListener(new ViewPropertyAnimatorListenerAdapter() {
                        @Override
                        public void onAnimationStart(View view) {
                        }

                        @Override
                        public void onAnimationEnd(View view) {
                        }
                    }).start();
        } else {
            Animation anim = AnimationUtils.loadAnimation(mView.getContext(), android.support.design.R.anim.design_snackbar_out);
            anim.setInterpolator(new FastOutSlowInInterpolator());
            anim.setDuration(ANIMATION_DURATION);
            anim.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationEnd(Animation animation) {
                }

                @Override
                public void onAnimationStart(Animation animation) {
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                }
            });
            mView.startAnimation(anim);
        }
    }

    public void setCartAdapter(CartListAdapter adapter) {
        this.adapter = adapter;
        if(listView.getHeaderViewsCount() == 0) {
            View head;
            head = LayoutInflater.from(mContext).inflate(R.layout.head_cart_view, null);
            head.findViewById(R.id.bt_clear).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                    builder.setTitle(R.string.clear_cart);
                    builder.setMessage(R.string.sure_to_clear_cart);
                    builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            CartView.this.adapter.clearCart();
                            sbv.hide();
                        }
                    });
                    builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
                    builder.show();
                }
            });
            listView.addHeaderView(head);
        }
        listView.setAdapter(adapter);
    }

    public void setOnOpenListener(CartListOpenListener openListener) {
        this.openListener = openListener;
    }

    @OnClick(R.id.bt_gocheck)
    protected void onCheck() {
        if (checkoutListener != null) {
            checkoutListener.onCheck();
        }
    }

    @OnClick(R.id.floatingButton)
    protected void onShowCart() {
        if (sbv.isPanelShowing()) {
            sbv.hide();
            return;
        }
        if(adapter == null || adapter.getCount() == 0){
            return;
        }
        if (openListener != null) {
            openListener.onOpen();
        }
        sbv.setVisibility(View.VISIBLE);
        sbv.displayPanel();
    }


    public void setOnCheckListener(CartCheckoutListener checkoutListener) {
        this.checkoutListener = checkoutListener;
    }

    public boolean hasAdapter() {
        return adapter!=null;
    }

    public CartListAdapter getAdapter() {
        return adapter;
    }

    public void reset() {
        setSummery("0.00");
        setQuantityText(0);
    }
}
